﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            String str = whichIsGood("www.baidu.com,www.163.com,www.sina.com.cn");

        }

        /// <summary>
        /// 找出ping毫秒数最少的那个ip
        /// </summary>
        /// <param name="ipList">adress,adress,adress</param>
        /// <returns>毫秒数</returns>
        public static string whichIsGood(string ipList)
        {
            string ret = "";
            string[] aryIpList;
            long nowValue = 0;
            long tmpValue = 0;
            int nowID = 0;

            if (ipList.IndexOf(",") >= 0)
            {
                aryIpList = ipList.Split(',');
                for (int i = 0; i < aryIpList.Length; i++)
                {
                    if (aryIpList[i] != "")
                    {
                        tmpValue = Ping(aryIpList[i]);
                        System.Console.WriteLine(aryIpList[i] + " -> " + tmpValue.ToString() + " ms");
                        if (nowValue == 0)
                        {
                            nowValue = tmpValue;
                            nowID = i;
                        }
                        else
                        {
                            if (nowValue > tmpValue)
                            {
                                nowValue = tmpValue;
                                nowID = i;
                            }
                        }
                    }
                }

                ret = aryIpList[nowID];

            }

            return ret;
        }

        /// <summary>
        /// Ping 一个网址、ip的方法，返回耗时
        /// </summary>
        /// <param name="ip">ip</param>
        /// <returns>毫秒数</returns>
        public static long Ping(string ip)//ping IP
        {
            long tt = 0;

            Ping ping = new Ping();

            PingOptions options = new PingOptions();

            options.DontFragment = true;

            string data = "Test Data!";

            byte[] buffer = Encoding.ASCII.GetBytes(data);

            int timeout = 2000; // Timeout 时间，单位：毫秒

            PingReply reply = ping.Send(ip, timeout, buffer, options);

            if (reply.Status == IPStatus.Success)
            {
                tt = reply.RoundtripTime;

            }

            else
            {

                tt = 9999;

            }

            return tt;

        }
    }
}
